// 定时器
function getTime(distance, self, callBack) {
    var time;
    return {
        start: function () {
            if (time) {
                return;
            }
            time = setInterval(callBack.bind(self), distance);
        },
        stop: function () {
            clearInterval(time);
            time = null;
        }
    }
}

/**
 * 生产规定范围内的随机值
 * @param {'最小值'} min 
 * @param {'最大值'} max 
 * */
function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

let startBtn = document.querySelector('.start');
let stopBtn = document.querySelector('.stop');
let overBtn = document.querySelector('.over');
// 游戏对象
var game = {
    dom: document.querySelector('.game'),
    isPause: true,
    isOver: false,
    speedUp:2500,//加速
    overDom: document.querySelector('.over'),
    gradeDom: document.querySelector('.grade'),
    speedUpDom: document.querySelector('.speedUp'),
    grade: 0,
    start: function () {
        sky.timer.start();
        land.timer.start();
        bird.wingTimer.start();
        bird.dropTimer.start();
        pillarSupervisor.start();
        testCeash.verifyTime.start();
        this.isPause = false;
    },
    stop: function () {
        sky.timer.stop();
        land.timer.stop();
        bird.wingTimer.stop();
        bird.dropTimer.stop();
        pillarSupervisor.stop();
        testCeash.verifyTime.stop();
        this.isPause = true;
    }
};
game.width = game.dom.clientWidth;
game.height = game.dom.clientHeight;


// 天空对象
var sky = {
    dom: document.querySelector('.game .sky'),
    left: 0,
}
sky.timer = getTime(16, sky, function () {
    // console.log(this,this.dom)
    this.left--;
    this.dom.style.left = this.left + 'px';
    if (this.left <= -game.width) {
        this.left = 0;
    }

})

// 大地对象
var land = {
    dom: document.querySelector('.game .land'),
    left: 0,
}
land.height = land.dom.clientHeight;
land.top = game.height - land.height;
land.dom.style.top = land.top + 'px';
land.timer = getTime(16, land, function () {
    // console.log(this,this.dom)
    this.left -= 2;
    this.dom.style.left = this.left + 'px';

    if (this.left <= -game.width) {
        this.left = 0;
    }

});

// 小鸟对象
var bird = {
    dom: document.querySelector('.game .bird'),
    height: 26,
    width: 33,
    left: 150,
    top: 150,
    wingState: 0,
    a: 0.001,
    v: 0,
    t: 16,
    show() {
        switch (this.wingState) {
            case 0:
                this.dom.style.backgroundPosition = "-8px -10px";
                break;
            case 1:
                this.dom.style.backgroundPosition = "-60px -10px";
                break;
            default:
                this.dom.style.backgroundPosition = "-113px -10px";
                break;
        }
        this.dom.style.left = this.left + "px";
        this.dom.style.top = this.top + "px";
    },
    setTop(top) {
        if (top < 0) {
            top = 0;
        } else if (top > (land.top - this.height)) {
            top = land.top - this.height;
        }
        // console.log(top, land.top, this.height)
        this.top = top;
        this.show();
    },
    jump() {
        this.v = -0.25;
    }
}
bird.wingTimer = getTime(120, bird, function () {
    this.wingState = (this.wingState + 1) % 3;
    this.show();

});
bird.dropTimer = getTime(bird.t, bird, function () {
    //计算移动距离
    var dis = this.v * this.t + 0.5 * this.a * this.t * this.t;
    //改变速度
    this.v = this.v + this.a * this.t;
    this.setTop(this.top + dis);
})

/**
 * 生产一个柱子
 * @param {'方向'} direction 
 * @param {'高度'} height 
 */
function Pillar(direction, height) {
    this.dom = document.createElement('div');
    this.top;
    this.width = 52;
    this.height = height;
    this.left = game.width;
    this.direction = direction;
    this.setStyle();
    this.show();
}
Pillar.prototype.setStyle = function () {
    if (this.direction == 'up') {
        this.top = land.top - this.height;
    } else {
        this.top = 0;
    }
    this.dom.className = 'pillar ' + this.direction;
    this.dom.style.width = this.width + 'px';
    this.dom.style.height = this.height + 'px';
    this.dom.style.top = this.top + 'px';
    game.dom.appendChild(this.dom);
}
Pillar.prototype.show = function () {
    this.dom.style.left = this.left + 'px';
}

/**
 * 生产一对柱子
 **/
function TwainPillar() {
    let minHeight = 60;
    let gap = 160;
    let maxHeight = land.top - minHeight - gap;
    this.H = getRandom(minHeight, maxHeight);
    // console.log(this.H,this.H - gap)
    this.up = new Pillar('up', this.H);
    this.down = new Pillar('down', land.top - this.H - gap);
    this.left = this.up.left;
    this.width = this.up.width;
    this.isGetGrade = false;
}
TwainPillar.prototype.show = function () {
    this.up.left = this.left;
    this.down.left = this.left;
    this.up.show();
    this.down.show();
}
TwainPillar.prototype.remove = function () {
    this.up.dom.remove();
    this.down.dom.remove();
}


/**
 * 柱子管理器
 * */
let pillarSupervisor = {
    pillars: []
}

// 添加柱子
pillarSupervisor.appPillar = getTime(game.speedUp, pillarSupervisor, function () { 
    this.pillars.push(new TwainPillar());
});

// 移动柱子
pillarSupervisor.movePillar = getTime(16, pillarSupervisor, function () {
    for (let i = 0; i < this.pillars.length; i++) {
        this.pillars[i].left -= 2;
        //   console.log(this.pillars[i].width)
        if (this.pillars[i].left <= -this.pillars[i].width) {
            this.pillars[i].remove();
            this.pillars.splice(i, 1);
            i--;
        } else {
            this.pillars[i].show();
        }
    }
});

// 开始移动和添加柱子
pillarSupervisor.start = function () {
    this.appPillar.start();
    this.movePillar.start();
}

// 暂停移动和添加柱子
pillarSupervisor.stop = function () {
    this.appPillar.stop();
    this.movePillar.stop();
}

// 检测碰撞器 + 分数记录
let testCeash = {
    verify() { // 碰撞返回true  不是返回false   
        if (bird.top >= (land.top - bird.height)) {
            // 与大地亲吻
            return true;
        }
        for (let i = 0; i < pillarSupervisor.pillars.length; i++) {
            if (this.validateBirdAndPipe(pillarSupervisor.pillars[i].up) || this.validateBirdAndPipe(pillarSupervisor.pillars[i].down)) {
                return true;
            }
            // 记录分数
            if (this.getGradesDevice(pillarSupervisor.pillars[i].up, pillarSupervisor.pillars[i].isGetGrade)) {
                pillarSupervisor.pillars[i].isGetGrade = true;
                game.gradeDom.innerHTML = ++game.grade;
                let boo = false;
                if (game.grade == 8) {
                    game.speedUp = 2000;
                    boo = true;
                } else if (game.grade == 15) {
                    game.speedUp = 1800;
                    boo = true;
                } else if (game.grade == 30) {
                    game.speedUp = 1500;
                    boo = true;
                }else if(game.grade > 30 && game.grade % 10 == 0){
                    game.speedUp = getRandom(1500,2500);
                    boo = true;
                }
                if(boo) {
                    game.speedUpDom.style.display = 'block';
                    setTimeout(() => {
                        game.speedUpDom.style.display = 'none';
                    }, 800);
                    // 重新计时，添加柱子
                    pillarSupervisor.appPillar.stop();
                    pillarSupervisor.appPillar = getTime(game.speedUp, pillarSupervisor, function () {
                        // console.log(game.speedUp.time)
                        this.pillars.push(new TwainPillar());
                    });
                    pillarSupervisor.appPillar.start();
                }
            }
        }
        return false;

    },
    validateBirdAndPipe(pillar) {
        let bx = bird.left + bird.width / 2;
        let by = bird.top + bird.height / 2;
        let px = pillar.left + pillar.width / 2;
        let py = pillar.top + pillar.height / 2;
        if (
            Math.abs(px - bx) <= (bird.width + pillar.width) / 2
            && Math.abs(py - by) <= (bird.height + pillar.height) / 2
        ) {
            return true;
        }
    },
    getGradesDevice(pillar, isGetGrade) {
        let bx = bird.left - bird.width / 2;
        let px = pillar.left + pillar.width;
        if (Math.abs(px - bx) <= (bird.width + pillar.width) / 2 && !isGetGrade) {
            return true;
        }

    }
}

testCeash.verifyTime = getTime(16, testCeash, function () {

    if (this.verify()) {
        game.stop();
        game.isOver = true;
        game.overDom.style.display = 'block';
    }
})




// 注册事件
// window.onkeydown = function (event) {
//     // console.log(event);
//     if (event.code == "Enter") {
//         if(game.isOver){
//             location.reload();
//             return;
//         }
//         if (game.isPause) {
//             startBtn.style.display = 'none';
//             stopBtn.style.display = 'block';
//             game.start();
//         } else {
//             startBtn.style.display = 'block';
//             stopBtn.style.display = 'none';
//             game.stop();
//         }

//     } else if (event.code == "Space") {
//         bird.jump();
//     }
// }

// 移动端事件 
startBtn.addEventListener('touchstart', () => {
    console.log('ok')
    startBtn.style.display = 'none';
    stopBtn.style.display = 'block';
    game.start();

}, false);
stopBtn.addEventListener('touchstart', () => {
    startBtn.style.display = 'block';
    stopBtn.style.display = 'none';
    game.stop();

}, false);


overBtn.addEventListener('touchstart', () => {
    location.reload();
}, false);

// 小鸟跳跃
document.addEventListener('touchstart', () => {
    console.log(document)
    if (game.isPause) return;
    bird.jump();
})